package com.icangya.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icangya.DAO.*;
import com.icangya.Utils.JSONUtils;
import com.icangya.Value.FootBall;
import com.icangya.Value.StaticValue;
import com.icangya.domain.*;
import com.icangya.service.IFootUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("FootUserServiceImpl")
public class FootUserServiceImpl implements IFootUserService{

    @Autowired
    private IUserFootDAO iUserDAO;
   @Autowired
   private IKicKBallDAO iKicBallDAO ;
    @Autowired
    private IBalanceDAO iBalanceDAO;
    @Autowired
    private ICommissionRecordDAO iCommissionRecordDAO;
    @Autowired
    private ICashRegisterDAO iCashRegisterDAO;
    @Autowired
    private IRechargeRecordDAO iRechargeRecordDAO;
    @Autowired
    private ICommissionFootDAO iCommissionFootDAO;
    @Autowired
    private IExpendRecordDAO iExpendRecordDAO;
    @Autowired
    private IProxyLevelDAO iProxyLevelDAO;
    @Autowired
    private IEditionInfoDAO iEditionInfoDAO;
    @Autowired
    private IGiftAdvertMoneyDAO iGiftAdvertMoneyDAO;
    @Autowired
    private IGiveMoneyRecordDAO iGiveMoneyRecordDAO;
    @Autowired
    private IFbUsermoodDAO iFbUsermoodDAO;
    @Autowired
    private IFbMoodImgDAO iFbMoodImgDAO;
    @Autowired
    private IFbCommentDAO iFbCommentDAO;
    @Autowired
    private  IFbTipDAO iFbTipDAO;
    @Autowired
    private  IFbMissionRecordDAO iFbMissionRecordDAO;
    @Autowired
    private  IFbTurntableRecordDAO iFbTurntableRecordDAO;
    @Autowired
    private  IFbUserMobileDAO iFbUserMobileDAO;

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    /*
    * 查询用户的信息
    */
    @Override
    public JSONObject selectUserByOpnId(String openId) {
        JSONObject jsonObject = new JSONObject();
        Object[] obj = iUserDAO.getNickName(openId);

        if (obj == null) {
            return null;
        }

        jsonObject.put("alert","");// 设置默认的
        FbTip fbTip= null;
        try {
            fbTip= iFbTipDAO.getFbTip();
        }catch (NullPointerException e){
            logger.info(e.getMessage()+"=======================e.getMessage()");
        }


       if(fbTip!=null) {
           jsonObject.put("alert", fbTip.getTipContent());
       }
        jsonObject.put("nickName",obj[0]);//获得用户昵称
        jsonObject.put("headimgurl",obj[1]);//用户头像
        jsonObject.put("openid",openId);
        jsonObject.put("missionCount",iFbMissionRecordDAO.getMissionRecordCount(new Timestamp(new Date().getTime()),openId));//任务个数
        jsonObject.put("turnCount",iFbTurntableRecordDAO.getFbTurntableRecordCount(openId));
        DecimalFormat format=new DecimalFormat("#0.##");
        double balanceMoney=iBalanceDAO.getBanlanceByOpenId(openId).getMoney();

        jsonObject.put("balanceMoney",balanceMoney);
//        jsonObject.put("balanceMoney",format.format(balanceMoney));
     //   double money=0.0;
        jsonObject.put("money",0);//赠送广告金
        //判断用户是否有赠送的广告金
        GiftAdvertMoney giftAdvertMoney= iGiftAdvertMoneyDAO.getGiftAdvertMoneyByOpenId(openId);
        if(giftAdvertMoney!=null && giftAdvertMoney.getGitAdvertMoney()>0){

            jsonObject.put("money",giftAdvertMoney.getGitAdvertMoney());//赠送广告金
        }

        // money=giftAdvertMoney.getGitAdvertMoney();
        //未领取的赠送广告金
       List<GiveMoneyRecord> list= iGiveMoneyRecordDAO.getGiveMoneyStatus(openId);
        JSONArray jsonArray=new JSONArray();
       if(list!=null){
           for (GiveMoneyRecord give:list) {
               JSONObject jsonObject1=new JSONObject();
               jsonObject1.put("id",give.getId());
               jsonObject1.put("gitMoney",give.getMoney());
               jsonObject1.put("giveType",give.getGiveType());
               jsonObject1.put("giveTime",give.getCreateTime());
               jsonArray.add(jsonObject1);
           }

       }
        jsonObject.put("giveMoneyList",jsonArray);//
        double expendMoney=iExpendRecordDAO.getExpendMoneyByOpenId(openId);
        //format.format(expendMoney)
        jsonObject.put("expendMoney",expendMoney);//用户支出金额
        double  commMoney=iCommissionFootDAO.selectUserCommis(openId).getMoney() ;

       String  money=format.format(commMoney);
//        BigDecimal big=new BigDecimal(bmoney);
//        double commMoney=big.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();//设置添加到数据库的金额只包含俩位小数
        jsonObject.put("commMoney",commMoney);//用户佣金
        return  jsonObject;
    }


    /**
     * 使用手机号码和密码，查询用户信息
     * @param mobilePhone
     * @param password
     * @return List<FBUserMobile>
     */
    @Override
    public List<FBUserMobile> queryUserByMobilePhoneAndPassword(long mobilePhone, String password) {

        List<FBUserMobile> fbUserMobileList = iFbUserMobileDAO.queryUserByMobilePhoneAndPassword(mobilePhone,password);

        return fbUserMobileList;
    }

    //我的页面获取用户详情
    @Override
    public JSONObject getUserMessage(String openId) {
        JSONObject jsonObject = new JSONObject();
//        User user=iUserDAO.selectUserByOpenId(openId);
        DecimalFormat format=new DecimalFormat("#0.##");
        double balanceMoney=iBalanceDAO.getBanlanceByOpenId(openId).getMoney();

        jsonObject.put("balanceMoney",balanceMoney);
        jsonObject.put("money",0);//赠送广告金
        //判断用户是否有赠送的广告金
        GiftAdvertMoney giftAdvertMoney= iGiftAdvertMoneyDAO.getGiftAdvertMoneyByOpenId(openId);
        if(giftAdvertMoney!=null && giftAdvertMoney.getGitAdvertMoney()>0){
            jsonObject.put("money",giftAdvertMoney.getGitAdvertMoney());//赠送广告金
        }
        double expendMoney=iExpendRecordDAO.getExpendMoneyByOpenId(openId);
        jsonObject.put("expendMoney",expendMoney);//用户支出金额
        jsonObject.put("commMoney",iCommissionFootDAO.selectUserCommis(openId).getMoney());//用户佣金
        jsonObject.put("openId",openId);
        jsonObject.put("cashCount", iCashRegisterDAO.getCountCashRecord(openId));//提现次数

        return jsonObject;
    }
//
//// 查询代理团队的客服二维码
//    @Override
//    public AgentImage getAgentImg(long proxyId) {
//
//        iAgentImageDAO.getAgentImageByAgentId(proxyId);
//
//
//
//        return null;
//    }

    @Override
    public User getByOpenId(String openId) {
        return iUserDAO.selectUserByOpenId(openId);
    }


    /*
    * 添加用户的信息
    */
    @Override
    public User addUser(User user) {

        User use=iUserDAO.get(iUserDAO.save(user));

        return use;
    }

    @Override
    public User updateUser(User userDO) {
        if (iUserDAO.update(userDO))
            return userDO;
        return null;

    }

    @Override
    public User getUserByUid(long uid) {
        return iUserDAO.selectUserByUid(uid);
    }


    /*
    *
    * 获取用户踢球的记录
    * */
    @Override
    public JSONObject getKicBallByOpenId(String openId) {
        List kicList;
        kicList= iKicBallDAO.getKicBallByOpenId(openId);
        JSONArray jsonArray=new JSONArray();

        for (KicKBall kic:(List<KicKBall>)kicList) {
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("id",kic.getId());
            jsonObject.put("amountMoney",kic.getAmountMoney());
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String time = format.format(kic.getKickBallTime());
            jsonObject.put("kickBallTimw",time);
            jsonObject.put("openId",kic.getOpenId());
            jsonArray.add(jsonObject);


        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("value",jsonArray);

        return jsonObject;
    }


    /*
    *
    * 添加用户踢球的记录
    * */

    @Override
    public JSONObject addKicKBall(KicKBall kib) {
        JSONObject jsonObject=new JSONObject();
        Balance balance= iBalanceDAO.getBanlanceByOpenId(kib.getOpenId());
        jsonObject.put("code",0);
        if(kib.getBetAmount()>balance.getMoney()){
            jsonObject.put("code",1);
//            jsonObject.put("error","用户余额不足");
            return jsonObject;
        }

        double money=kib.getAmountMoney()-kib.getBetAmount();
        if(kib.getAmountMoney()==kib.getBetAmount())
            money=0;
     //   if(balance.getMoney()-money>0){
            KicKBall kicKBall= iKicBallDAO.get(iKicBallDAO.save(kib));
            if(kicKBall==null)
                return null;



            //添加用户的支出记录
            iExpendRecordDAO.save(new ExpendRecord(kib.getOpenId(),StaticValue.FootBall,kib.getBetAmount(),kib.getKickBallTime()));

//            //踢球成功之后给上级用户追加佣金
//            addAgencyComm(kib.getOpenId(),kib.getBetAmount());
            //添加用户广告金记录
            //  Balance balance= iBalanceDAO.getBanlanceByOpenId(kib.getOpenId());
//        if(balance==null){//用户不存在广告金记录，就添加
//            iBalanceDAO.save(new Balance(kib.getOpenId(),kib.getAmountMoney(),kib.getKickBallTime(),new Timestamp(new Date().getTime())));
//        }else{
//        DecimalFormat format=new DecimalFormat("#0.##");
//        BigDecimal big=new BigDecimal(money);
//        money=big.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();//设置添加到数据库的金额只包含俩位小数
            //format.format(money))
            iBalanceDAO.updateBanlanceByMoney(kib.getOpenId(),money);
//        }
     //   }


        Balance bal= iBalanceDAO.getBanlanceByOpenId(kib.getOpenId());
      jsonObject.put("money", bal.getMoney()) ;
      jsonObject.put("amountMoney",kib.getAmountMoney());
        return jsonObject;
    }





    @Override
    public ProxyLevel getProxyLevel(Long uid) {
        return iProxyLevelDAO.getSuperiorUserByUid(uid);
    }

    @Override
    public ProxyLevel saveProxyLevel(ProxyLevel proxyLevel) {
        return iProxyLevelDAO.get(iProxyLevelDAO.save(proxyLevel));
    }



    @Override
    public JSONObject getProxyNum(long uid) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("count1", iProxyLevelDAO.getFirstCount(uid));
        jsonObject.put("count2", iProxyLevelDAO.getSecondCount(uid));
        jsonObject.put("count3", iProxyLevelDAO.getThirdCount(uid));
        return jsonObject;
    }




    @Override
    public Boolean cash(String openId,double money ) {

//        Commission commission=  iCommissionFootDAO.selectUserCommis(openId);
//        JSONObject jsonObject=new JSONObject();
        //判断用户的余额是否充足
       // if(commission.getMoney()>=money){
          //  double cashMoney= commission.getMoney()-money;
//            int result=  iCommissionFootDAO.changeMoney(openId,0);
//            if(result>0){

                //添加用户提现记录
                iCashRegisterDAO.save( new CashRegister(openId,money, new Timestamp( new Date().getTime()),0));//0:提现成功
                return true;

//            }
       // }

//        return false;



    }

    @Override
    public Boolean rechargeRecord(String openId, Double money) {

       int result= iBalanceDAO.updateBanlanceByMoney(openId,money);
       if(result>0){
           //充值成功，添加用户的充值记录
           iRechargeRecordDAO.save(new RechargeRecord(openId,money, new Timestamp( new Date().getTime()),0));

           //充值成功之后给上级用户追加佣金
            addAgencyComm(openId,money);

           return true;

       }
           //充值失败，添加用户的充值记录
           iRechargeRecordDAO.save(new RechargeRecord(openId,money, new Timestamp( new Date().getTime()),1));
        return false;
    }


    public void addAgencyComm(String openId,double amountMoney){

        Commission commission=new Commission();
        //获取用户的代理信息
        ProxyLevel proxyLevel=  iProxyLevelDAO.getSuperiorUserByOpenId(openId);

        if(proxyLevel!=null){


            //几级用户的信息
            long first=proxyLevel.getFirstLevel();
            long second=proxyLevel.getSecondLevel();
            long third=proxyLevel.getThirdLevel();
            Timestamp now = Timestamp.valueOf(LocalDateTime.now());
            //一级用户id不为0时，设置一级用户的佣金记录和添加返现佣金
            //返现的金额
            double returnMoney=0.0;
            if(first!=0){

                returnMoney=amountMoney* FootBall.first_level;

                BigDecimal big=new BigDecimal(returnMoney);
                returnMoney=big.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();//设置添加到数据库的金额只包含俩位小数


                String firstOpenId=iUserDAO.selectUserByUid(first).getOpenId();//一级用户的信息
                //增加一级用户的佣金记录
                iCommissionRecordDAO.save(new CommissionRecord(firstOpenId, StaticValue.AGENCYCOMM,returnMoney,now));
                commission= iCommissionFootDAO.selectUserCommis(firstOpenId);
                returnMoney= commission.getMoney()+returnMoney;
                //增加一级用户的金额
                int result= iCommissionFootDAO.changeMoney(firstOpenId,returnMoney);

                //二级用户id不为0时，设置二级用户的佣金记录和添加返现佣金
                if(second!=0){
                    //二级返现的金额
                    returnMoney=amountMoney* FootBall.second_level;
                    BigDecimal big2=new BigDecimal(returnMoney);
                    returnMoney=big2.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();//设置添加到数据库的金额只包含俩位小数

                    String secondOpenId=iUserDAO.selectUserByUid(second).getOpenId();//二级用户的信息
                    //增加二级用户的佣金记录
                    iCommissionRecordDAO.save(new CommissionRecord(secondOpenId, StaticValue.AGENCYCOMM,returnMoney,now));
                    commission= iCommissionFootDAO.selectUserCommis(secondOpenId);
                    returnMoney= commission.getMoney()+returnMoney;
                    //增加二级用户的金额
                    iCommissionFootDAO.changeMoney(secondOpenId,returnMoney);

                    //三级用户id不为0时，设置三级用户的佣金记录和添加返现佣金
                    if(third!=0){
                        //三级返现的金额
                        returnMoney=amountMoney* FootBall.third_level;
                        BigDecimal big3=new BigDecimal(returnMoney);
                        returnMoney=big3.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();//设置添加到数据库的金额只包含俩位小数

                        String thirdOpenId=iUserDAO.selectUserByUid(third).getOpenId();//三级用户的信息
                        //添加三级用户的佣金记录
                        iCommissionRecordDAO.save(new CommissionRecord(thirdOpenId,StaticValue.AGENCYCOMM,returnMoney,now));
                        commission= iCommissionFootDAO.selectUserCommis(thirdOpenId);
                        returnMoney= commission.getMoney()+returnMoney;
                        //增加三级用户的佣金金额
                        iCommissionFootDAO.changeMoney(thirdOpenId,returnMoney);
                    }


                }

            }


        }


    }
    @Override
    public JSONObject getEditionInfo() {
        EditionInfo editionInfo= iEditionInfoDAO.getEditionInfo();
        JSONObject jsonObject=new JSONObject();
        if(editionInfo==null){
            jsonObject.put("error_code",1);
            return jsonObject;
        }

        jsonObject.put("error_code",0);
        jsonObject.put("versionNum",editionInfo.getVersionNum());
        jsonObject.put("versionContent",editionInfo.getVersionContent());
        jsonObject.put("createTime",editionInfo.getCreateTime());

        return jsonObject;
    }

    @Override
    public List<User> getAllUser() {

        return iUserDAO.getAllUser();

    }

    //查询所有用户信息
    @Override
    public List<User> findAllUser() {

        List<Object[]> objs= iUserDAO.findAllUser();
        if(objs==null)
            return null;

        List<User> list=new ArrayList<User>();
//        String openId, String nickName, String headImgUrl, Timestamp createTime, Long parentId, String qrCode, Long proxyId
//        u.openId,u.nickName,u.headImgUrl,u.createTime,u.parentId,u.proxyId
        for (Object[] obj:objs) {
            User user=new User();
            user.setOpenId(obj[0].toString());
            user.setNickName(obj[1].toString());
            user.setHeadImgUrl(obj[2].toString());
            user.setCreateTime(Timestamp.valueOf(obj[3].toString()));
            user.setParentId(Long.valueOf(obj[4].toString()));
            user.setProxyId(Long.valueOf(obj[5].toString()));
            user.setQrCode("");
            list.add(user);
        }
        return list;
    }

    //是第一次充值，就赠送广告金
    @Override
    public JSONObject setGitMoney(String openId, double gitMoney,double money) {
        //修改
        //获取用户当前的余额
        Balance balance= iBalanceDAO.getBanlanceByOpenId(openId);
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("money",balance.getMoney());
        //获取用户充值每种金额的记录

     List list=  iRechargeRecordDAO.getRechargeByOpenIdOrMoney(openId,money);
     if(list.size() > 0 ){
         jsonObject.put("bool",false);
         return jsonObject;
     }

     //list.size()====0          增加用户赠送广告金记录
        logger.info("充值金额记录的次数================================"+list.size());
        GiveMoneyRecord giveMoneyRecord= iGiveMoneyRecordDAO.get(iGiveMoneyRecordDAO.save(new GiveMoneyRecord(openId,gitMoney,"首充赠送广告金",new Timestamp(new Date().getTime()),0)));
         System.out.println(giveMoneyRecord.getMoney()+"......................");
        jsonObject.put("bool",true);
        return jsonObject;
//        //修改
//        //获取用户当前的余额
//        Balance balance= iBalanceDAO.getBanlanceByOpenId(openId);
//        JSONObject jsonObject=new JSONObject();
//        jsonObject.put("money",balance.getMoney());
//        //获取用户充值每种金额的记录
//     List list=  iRechargeRecordDAO.getRechargeByOpenIdOrMoney(openId,money);
//         if(list.size() > 0 ){
//             jsonObject.put("bool",false);
//             return jsonObject;
//         }
//     //增加用户广告金记录
//        GiveMoneyRecord giveMoneyRecord= iGiveMoneyRecordDAO.get(iGiveMoneyRecordDAO.save(new GiveMoneyRecord(openId,gitMoney,"首充赠送广告金",new Timestamp(new Date().getTime()),0)));
//         System.out.println( giveMoneyRecord.getMoney()+"......................");
//        jsonObject.put("bool",true);
//     return jsonObject;
    }

    @Override
    public Object[] getNickName(String openId) {
        return iUserDAO.getNickName(openId);
    }

    //点击邮箱获取赠送广告金
    @Override
    public Boolean setUserGitMoney(String openId, long id) {


          GiveMoneyRecord giveMoneyRecord=  iGiveMoneyRecordDAO.get(id);
          if(giveMoneyRecord.getStatus()==1)
              return false;

         // giveMoneyRecord.setMoney(0);
          giveMoneyRecord.setStatus(1);//赠送广告金被领取，修改状态为1
        boolean bool= iGiveMoneyRecordDAO.update(giveMoneyRecord);
        if(bool){//修改成功，将金额添加到用户赠送的广告金表中
           int result= iGiftAdvertMoneyDAO.updateGiftAdvertMoney(openId,giveMoneyRecord.getMoney());
           if(result>0)
                return true;
        }

        return false;
    }

    //用户今天还能提现的额度
    @Override
    public double checkCashMoneyAmount(String openId) {
       double cashMoney= iCashRegisterDAO.getSumCashMoney(openId);
       double rechargeMoney=iRechargeRecordDAO.getSumRechargeMoney(openId);
       double money=rechargeMoney*2 - cashMoney;
        logger.info("用户今天所能提现的额度 "+money);
        return money;
    }

    @Override
    public JSONObject saveUserMood(FbUsermood fbUsermood, List<FbMoodImg> fbMoodImgList) {
        try{
            long id= (long) iFbUsermoodDAO.save(fbUsermood);

            for (int i =0;i<fbMoodImgList.size();i++){
                fbMoodImgList.get(i).setMoodId(id);
                iFbMoodImgDAO.save(fbMoodImgList.get(i));
            }
            return JSONUtils.getRoot(0,"success","添加成功！");
        }catch (Exception e){
            return JSONUtils.getRoot(1,"faild",e.getMessage());
        }
    }

    @Override
    public List selectUsermoods(String openId,int startPage) {
        List fbUsermoodList = null;
        try {
            fbUsermoodList = iFbUsermoodDAO.selectUsermoods(openId,startPage);
            return fbUsermoodList;
        }catch (Exception e){
            logger.info(e.getMessage());
        }
       return fbUsermoodList;
    }

    @Override
    public FbUsermood getFbUserMoodById(Long id) {


        FbUsermood fbUsermood = iFbUsermoodDAO.get(id);

        return fbUsermood;

    }

    @Override
    public List<FbMoodImg> selectFbMoodImgsByMoodId(Long id) {

        List<FbMoodImg> fbMoodImgList = iFbMoodImgDAO.selectFbMoodImgsByMoodId(id);

        return fbMoodImgList;

    }

    @Override
    public JSONObject saveComment(FbComment fbComment) {
        try {
            iFbCommentDAO.save(fbComment);
            return JSONUtils.getRoot(0,"SUCCESS","添加成功");
        }catch (Exception e){

            return JSONUtils.getRoot(0,"FAILD",e.getMessage());
        }
    }

    @Override
    public List<FbComment> selectCommentsByMoodId(Long moodId) {

        List<FbComment> fbCommentsList = iFbCommentDAO.selectFbCommentsByMoodId(moodId);

        return fbCommentsList;

    }

    @Override
    public boolean updateMobilePhone(FBUserMobile fbUserMobile) {
//        FBUserMobile fbUserMobile = iFbUserMobileDAO.get(id);
//        fbUserMobile.setMobilePhone(mobilePhone);
        return iFbUserMobileDAO.update(fbUserMobile);
    }

    @Override
    public List<FBUserMobile> queryMobilePhoneByOpenid(String openid) {
        return  iFbUserMobileDAO.queryMobilePhoneByOpenid(openid);
    }


    /**
     * 根据mobilePhone查询记录
     * @param mobilePhone
     * @return
     */
    @Override
    public List<FBUserMobile> queryMobilePhoneByMobilePhone(long mobilePhone){
        return iFbUserMobileDAO.queryMobilePhoneByMobilePhone(mobilePhone);
    }
}
